import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
import 'package:flutter_ncsjqz_getx/page_common/show_video_page.dart';
import 'package:flutter_ncsjqz_getx/widget/app_bar_widget.dart';
import 'package:flutter_ncsjqz_getx/widget/base_widget.dart';
import 'package:flutter_ncsjqz_getx/widget/dialog_current_project_widget.dart';
import 'package:flutter_ncsjqz_getx/widget/gradient_button.dart';
import 'package:flutter_ncsjqz_getx/widget/ink_widget.dart';
import 'package:flutter_ncsjqz_getx/widget/row_line_widget.dart';
import 'package:flutter_ncsjqz_getx/widget/tab_widget.dart';
import 'package:get/get.dart';

import 'after_info/after_info_view.dart';
import 'cancel_order/cancel_order_view.dart';
import 'order_logic.dart';

/// <summary>
/// todo: 订单管理
/// author：zwb
/// dateTime： 2021/11/9 17:46
/// filePath： lib/page/my/order/order_view.dart
/// desc:
/// <summary>
///
class OrderManagePage extends StatefulWidget {
  final int? currentIndex; // 订单分类索引  1 == "待付款", 2 == "已完成", 3 == "退款", 4 == "退款中"
  OrderManagePage({this.currentIndex:0});
  @override
  _OrderManagePageState createState() => _OrderManagePageState();
}

class _OrderManagePageState extends State<OrderManagePage> {
  final logic = Get.put(OrderLogic());
  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    logic.currentIndex = widget.currentIndex!;
    logic.getOrderListData();
    logic.wxEvent();
    logic.update();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: appBarWidget(
        title: "订单管理"
      ),
      body: GetBuilder<OrderLogic>(
        builder: (controller) {
          return Column(
            children: [
              tab(
                tabs: logic.tabs,
                currentIndex: logic.currentIndex,
                bgColor: Colors.white,
                width: Get.width / 4,
                onTap: (v){
                  logic.setCurrentIndex(v);
                }
              ),

              Expanded(
                child: baseScaffoldWidget(
                  onRefresh: () async{
                    logic.getOrderListData();
                  },
                  child: ListView(
                    shrinkWrap: true,
                    padding: EdgeInsets.all(15),
                    children: List.generate(logic.orderData.length, (index){
                      return InkWell(
                        onTap: (){
                          // 退款详情 退款售后状态的订单才进入
                          openDetails(index);
                        },
                        child: Container(
                          width: Get.width,
                          padding: EdgeInsets.all(15),
                          margin: EdgeInsets.only(bottom: 5),
                          decoration: BoxDecoration(
                            color: Colors.white,
                            borderRadius: BorderRadius.circular(10),
                            boxShadow: [
                              BoxShadow(
                                  color: Colors.grey.shade300,
                                  blurRadius: 3,
                                  spreadRadius: 3
                              ),
                            ],
                          ),
                          child: Column(
                            mainAxisAlignment: MainAxisAlignment.spaceBetween,
                            crossAxisAlignment: CrossAxisAlignment.end,
                            children: [
                              Row(
                                children: [
                                  InkWidget.imgNet("${logic.orderData[index].img ?? ''}",width: 100,height: 100,fit: BoxFit.cover,borderRadius: BorderRadius.circular(5)),
                                  Container(
                                    width: Get.width - 100 - 60,
                                    height: 100,
                                    padding: EdgeInsets.only(left: 10),
                                    child: Column(
                                      mainAxisAlignment: MainAxisAlignment.spaceBetween,
                                      crossAxisAlignment: CrossAxisAlignment.start,
                                      children: [
                                        Row(
                                          crossAxisAlignment: CrossAxisAlignment.start,
                                          mainAxisAlignment: MainAxisAlignment.spaceBetween,
                                          children: [
                                            Expanded(child: InkWidget.title("${logic.orderData[index].title ?? ''}",maxLines: 2,fonSize: 16),),
                                            statusText(index),
                                          ],
                                        ),

                                        Column(
                                          crossAxisAlignment: CrossAxisAlignment.start,
                                          children: [
                                            InkWidget.text("规格：${logic.orderData[index].sku ?? ''}  数量：${logic.orderData[index].count ?? ''}",maxLines: 2,fonSize: 12,color: Colors.grey),
                                            InkWidget.title("${logic.orderData[index].price ?? ''}",color: Colors.red,fonSize: 14),
                                          ],
                                        ),
                                      ],
                                    ),
                                  ),
                                ],
                              ),
                              SizedBox(height: 5,),
                              buttonRow(index),
                            ],
                          ),
                        ),
                      );
                    }),
                  ),
                ),
              ),
            ],
          );
        },
      )
    );
  }

  @override
  void dispose() {
    Get.delete<OrderLogic>();
    if(logic.streamSubscription!=null){
      logic.streamSubscription!.cancel();
    }
    super.dispose();
  }

  /// 按钮
  buttonRow(int index) {
    // 退货退款
    if(logic.orderData[index].status == 30 ||
        logic.orderData[index].status == 31 ||
        logic.orderData[index].status == 13 ||
        logic.orderData[index].status == 22) return SizedBox();
    // 已完成
    if(logic.orderData[index].status == 2) return SizedBox(
      height: 30,
      child: OutlineButton(
        onPressed: (){},
        shape: StadiumBorder(),
        child: InkWidget.text("我的农场",color: Colors.green),
        borderSide: BorderSide(color: Colors.green),
      ),
    );
    // 待付款
    return SizedBox(
      child: Row(
        mainAxisAlignment: MainAxisAlignment.end,
        children: [
          Offstage(
            offstage: logic.orderData[index].status != 11,
            child: OutlineButton(onPressed: (){
              showDialogGetx(
                  subTitle: "取消订单后不可恢复，是否确定取消",
                  btnText: "确定取消",
                  okTap: () async{
                    logic.canOrder(int.parse(logic.orderData[index].id!));
                  }
              );
            },shape: StadiumBorder(),child: InkWidget.text("取消订单",color: Colors.grey),borderSide: BorderSide(color: Colors.grey),),
          ),
          SizedBox(width: 15,),
          Offstage(
            offstage: logic.orderData[index].status != 11,
            child: OutlineButton(onPressed: (){
              bottomMoneyPay(index);
            },shape: StadiumBorder(),child: InkWidget.text("立即付款",color: Colors.green),borderSide: BorderSide(color: Colors.green),),
          ),
          Offstage(
            offstage: logic.orderData[index].status != 41,
            child: Row(
              children: [
                OutlineButton(onPressed: (){
                  Get.to(()=>CancelOrderPage(orderModel: logic.orderData[index],))!.then((value) => logic.getOrderListData());
                },shape: StadiumBorder(),child: InkWidget.text("申请退款",color: Colors.grey),borderSide: BorderSide(color: Colors.grey),),
                SizedBox(width: 15,),
                OutlineButton(onPressed: (){
                  Get.to(()=>ShowVideoPage(title: "${logic.orderData[index].title}",));
                },shape: StadiumBorder(),child: InkWidget.text("我的农场",color: Colors.green),borderSide: BorderSide(color: Colors.green),),
              ],
            ),
          ),
        ],
      ),
      height: 30,
    );
  }

  /// 右上角状态标识
  statusText(index) {
    String text = "";
    Color textColor = Colors.white;
    // ORDER_INIT(10, "初始化"),
    // ORDER_WAIT_PAY(11, "等待支付"),
    // ORDER_PAY_FAIL(12, "支付失败"),
    // ORDER_CANCEL(13, "取消订单"),
    // ORDER_PAY_SUCCESS(14, "支付成功"),
    //
    // WAIT_DELIVER_GOODS(20, "等待发货"),
    // WAIT_RECEIVE(21, "待收货"),
    // APPLY_CANCEL_ORDER(22, "申请退货"),
    // REJECT_CANCEL_ORDER(23, "拒绝退货"),
    //
    // WAIT_REFUND(30, "等待退款"),
    // REFUNDED(31, "商家已退款"),
    // PLATFORM_REFUNDED(32, "平台同意退款"),
    // REJECT_REFUNDED(33, "平台拒绝退款"),
    //
    // WAIT_EVALUATE(41, "等待评价"),
    // EVALUATE_NEED(42, "已评价"),
    //
    // ORDER_CLOSE(99, "订单关闭");
    if(logic.orderData[index].status == 11){
      text = "待付款"; // 5分钟未支付自动取消订单
      textColor = Colors.red;
    }
    if(logic.orderData[index].status == 41){
      text = "已完成";
      textColor = Colors.green;
    }
    if(logic.orderData[index].status == 22){
      text = "申请退货";
      textColor = Colors.black45;
    }
    if(logic.orderData[index].status == 30){
      text = "退款中";
      textColor = Colors.black45;
    }
    if(logic.orderData[index].status == 32){
      text = "已退款";
      textColor = Colors.black45;
    }
    if(logic.orderData[index].status == 33){
      text = "拒绝退款";
      textColor = Colors.red;
    }
    if(logic.orderData[index].status == 13){
      text = "已取消";
      textColor = Colors.black45;
    }
    return InkWidget.text("$text",height: 1.5,color: textColor);
  }

  bottomMoneyPay(int index){
    Get.bottomSheet(
      GetBuilder<OrderLogic>(
        builder: (controller) {
          List payType = ["微信支付","支付宝支付"];
          List payIcon = ["wx.png","zfb.png","zfb.png"];
          double height = payType.length < 3 ?  280 : 345;
          return SingleChildScrollView(
            physics: NeverScrollableScrollPhysics(),
            child: Material(
              child: Container(
                height: height,
                color: Colors.white,
                padding: EdgeInsets.all(15),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Center(
                      child: SizedBox(
                        height: 60,
                        child:InkWidget.title("\n￥${logic.orderData[index].price! * logic.orderData[index].count!}",fonSize: 25,color: Colors.black),
                      ),
                    ),
                    InkWidget.title("\n选择支付方式"),
                    /// todo：支付方式
                    Expanded(
                      child: ListView(
                        shrinkWrap: true,
                        children: List.generate(payType.length, (index){
                          return rowBaseWidget(
                              left: Row(
                                children: [
                                  InkWidget.imgAsset("${payIcon[index]}",width: 22,fit: BoxFit.fill),
                                  InkWidget.text(" ${payType[index]}"),
                                ],
                              ),
                              height: 45,
                              right:  InkWidget.imgAsset("select.png",width: 20,color: logic.payType != index ? Colors.white:null),
                              padding: EdgeInsets.all(0),
                              onTap: (){
                                logic.setPayType(index);
                              }
                          );
                        }),
                      ),
                    ),
                    Center(
                      child: SizedBox(
                        width: Get.width * 0.7,
                        child: gradientButton("确 定",onTap: (){
                          logic.orderPay(logic.orderData[index]);
                        },circular: 40),
                      ),
                    ),
                  ],
                ),
              ),
              color: Colors.transparent,
            ),
          );
        },
      ),
      enableDrag: false,
      isScrollControlled: true,
    ).then((value) {
      logic.setPayType(0);
    });
  }

  openDetails(index){
     // 进入退款详情
    if(logic.orderData[index].status == 33 || logic.orderData[index].status == 32 || logic.orderData[index].status == 30 || logic.orderData[index].status == 22){
      Get.to(()=> AfterInfoPage(orderModel: logic.orderData[index],));
    }
  }
}

/// todo：订单model
class OrderModel{
  String? title;
  String? img;
  String? id;
  String? sku;
  int? count;
  int? status;
  double? price;
  dynamic orderNo;
  String? date;
  OrderModel({this.date,this.title,this.orderNo, this.img, this.id,this.price, this.sku, this.count,
    this.status});
}